

import logging

import pymongo
import rpyc
from rpyc.utils import server

from dexen.common import remoting, constants
from dexen.server.backend import core, resource_manager as res_mgr



_core = None


class ServerBackendEndPoint(remoting.BaseEndPoint):
    def on_connect(self):
        pass

    def on_disconnect(self):
        pass

    def create_job(self, user_name, job_name):
        _core.create_job(user_name, job_name)

    def delete_job(self, user_name, job_name):
        _core.delete_job(user_name, job_name)

    def run_job(self, user_name, job_name):
        _core.run_job(user_name, job_name)

    def stop_job(self, user_name, job_name):
        _core.stop_job(user_name, job_name)

    def get_jobs(self, user_name):
        return _core.get_jobs(user_name)

    def register_task(self, user_name, job_name, task):
        task = rpyc.classic.obtain(task)
        _core.register_task(user_name, job_name, task)

    def deregister_task(self, user_name, job_name, task_name):
        _core.deregister_task(user_name, job_name, task_name)

    def register_node(self, address):
        address = rpyc.classic.obtain(address)
        return _core.register_node(address)

    def register_worker(self, address, worker_name):
        address = rpyc.classic.obtain(address)
        _core.register_worker(address, worker_name)


def start(db_addr):
    global _core
    db_client = pymongo.MongoClient(db_addr.ip, db_addr.port)
    _core = core.ServerCore(res_mgr.ResourceManager(), db_client)
    _core.setDaemon(True)
    _core.start()

    server_backend_endpoint = server.ThreadedServer(
                                ServerBackendEndPoint,
                                port=constants.SERVER_BACKEND_PORT,
                                protocol_config=remoting.DEFAULT_CONFIG,
                                logger=logging.getLogger(__name__+"."+
                                                    "ServerBackendEndPoint"))

    server_backend_endpoint.start()
